<template>
    <div class="createVue">
         <!-- 顶部步骤 -->
         <div class="stepVue relative">
            <span style="font-weight: 600; position: absolute; left: 0; top: 50%; transform: translateY(-50%); color: #333;">群发任务名: {{ $route.query.taskName }}</span>
            <div class="flex_center">
                <div class="flex_column align_center">
                    <div class="dot" :class="{active: current===1}">1</div>
                    <span :class="{textActive: current===1}">选择接收消息对象</span>
                </div>
                <div class="line"></div>
                <div class="flex_column align_center">
                    <div class="dot" :class="{active: current===2}">2</div>
                    <span :class="{textActive: current===2}">设置消息内容</span>
                </div>
                <div class="line"></div>
                <div class="flex_column align_center"> 
                    <div class="dot" :class="{active: current===3}">3</div>
                    <span :class="{textActive: current===3}">完成</span>
                </div>
            </div>  
            <div class="chooseVue" @click="toChoose" v-if="current===1">选择历史接收的好友</div> 
        </div>
        <div class="contentVue">
            <!-- 第一步 -->
            <template v-if="current===1">
                <!-- 筛选 -->
                <div class="searchVue flex">
                    <el-input v-model="key" placeholder="搜索好友" style="width: 200px;" :clearable="true" prefix-icon="el-icon-search" @input="reStart"></el-input>
                    <div class="flex align_center" style="height: 40px;">
                        <div style="font-weight: 600; padding-left: 15px; font-size: 13px;">快速查找</div>
                        <span style="padding-left: 15px; cursor: pointer; font-size: 13px;" :class="{active: selectName==='全部'}" @click="fastSearch(1, '全部')">全部</span>
                        <span style="padding-left: 15px; cursor: pointer; font-size: 13px;" :class="{active: selectName==='有备注'}" @click="fastSearch(2, '有备注')">有备注</span>
                        <span style="padding-left: 15px; cursor: pointer; font-size: 13px;" v-for="item in words" :key="item" :class="{active: selectName===item}" @click="fastSearch(3, item)">{{ item }}</span>
                    </div>
                </div>        
                <div class="listVue">
                    <div class="content">
                        <div class="thVue flex">
                            <div class="li flex_center align_center" style="width: 80px; line-height: 40px;">
                                <img src="../../assets/S2.png" style="width: 20px; height: 20px; cursor: pointer;" v-if="isCurrentPage"  @click="cancelCurrentPage">
                                <img src="../../assets/S1.png" style="width: 20px; height: 20px; cursor: pointer;" v-else  @click="selectCurrentPage">
                                <span style="font-weight: 600; padding-left: 5px;">当前页</span>
                            </div>
                            <div class="li" style="width: 200px; line-height: 40px; text-align: center; font-weight: 600;">微信名</div>
                            <div class="li" style="flex: 1; line-height: 40px; text-align: center;">
                                <el-dropdown trigger="click" @command="handleTagCommand">
                                    <span class="el-dropdown-link" style="cursor: pointer;color: #333; font-weight: 600;">
                                        {{ tag || "标签" }}<i class="el-icon-caret-bottom el-icon--right" style="color: #333; font-weight: 600;"></i>
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item v-for="item in tags" :key="item" :command="item">{{ item }}</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                            <div class="li" style="width: 200px;; line-height: 40px; text-align: center;">
                                <el-dropdown trigger="click" @command="handleCategoryCommand">
                                    <span class="el-dropdown-link" style="cursor: pointer;color: #333; font-weight: 600;">
                                        {{ category || "分组" }}<i class="el-icon-caret-bottom el-icon--right" style="color: #333; font-weight: 600;"></i>
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                            <el-dropdown-item v-for="item in categoryList" :key="item.id" :command="item">{{item.name}}</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                            <div class="li" style="width: 100px;; line-height: 40px; text-align: center;">
                                <el-dropdown trigger="click" @command="handleChatCommand">
                                    <span class="el-dropdown-link" style="cursor: pointer;color: #333; font-weight: 600;">
                                        {{ chatName || "聊天类型" }}<i class="el-icon-caret-bottom el-icon--right" style="color: #333; font-weight: 600;"></i>
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item v-for="item in chatTypes" :key="item.name" :command="item">{{item.name}}</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                        </div>
                        <div class="tdContent">
                            <div class="tdVue flex" v-for="(item, index) in list" :key="index">
                                <div class="li" style="width: 80px; line-height: 50px; padding-left: 7px;">
                                    <img src="../../assets/S2.png" style="width: 20px; height: 20px; cursor: pointer;" v-if="JSON.stringify($store.state.selectList).includes(JSON.stringify(item))" @click="removeFun(item)">
                                    <img src="../../assets/S1.png" style="width: 20px; height: 20px; cursor: pointer;" v-else  @click="selectFun(item)">
                                </div>
                                <div class="li line-1" style="width: 200px; line-height: 50px; text-align: center; font-size: 13px; padding: 0 10px;">{{item.type===1 ? item.groupName : item.friendWechatName}}</div>
                                <div class="li flex_center align_center flex_1" style="overflow: hidden;">
                                    <template v-if="item.tag">
                                        <el-tag type="info" size="mini" v-for="(ver, i) in item.tag.split(',')" :key="i">{{ ver }}</el-tag>
                                    </template> 
                                </div>
                                <div class="li" style="width: 200px; line-height: 50px; text-align: center; font-size: 13px;">{{ item.categoryName }}</div>
                                <div class="li" style="width: 100px; line-height: 50px; text-align: center; font-size: 13px;">{{ ["私聊", "群聊"][item.type] }}</div>
                            </div>
                        </div>
                    </div>
                    <!-- 分页 -->
                    <div class="botVue flex_between align_center">
                        <div class="allBtn" v-if="isAll" @click="$store.state.selectList = []; isAll = false; isCurrentPage = false"><span>清空已选择</span></div>
                        <div class="allBtn" v-else  @click="selectAll">
                            <span class="el-icon-loading" v-if="selectLoading"></span>
                            <span v-else>选择所有好友</span>
                        </div>
                        <div class="paginationVue flex_center align_center">
                            <el-pagination background layout="total, prev, pager, next" :total="total" :page-size="pageSize"  @current-change="handlePageChange"></el-pagination>
                        </div>
                        <div class="flex align_center">
                            <el-button size="mini" type="cancel" @click="$router.go(-1)">返回</el-button>
                            <el-button size="mini" type="next" @click="nextFun(1)">下一步</el-button>
                        </div>
                    </div>
                </div>

                <!-- 已选 -->
                <div class="selectVue">
                    <el-tag v-for="tag in $store.state.selectList" :key="tag.name" closable type="info" size="mini" @close="handleClose(tag)">{{tag.type===0 ? tag.friendWechatName : tag.groupName}}</el-tag>
                </div>
            </template>

            <!-- 第二步 -->
            <template v-if="current===2">
                <div class="inpContent" ref="msgRef">
                    <!-- 已选 -->
                    <div class="selectVue ">
                        <el-tag v-for="tag in $store.state.selectList" :key="tag.name" closable type="info" size="mini" @close="handleClose(tag)">{{tag.type===0 ? tag.friendWechatName : tag.groupName}}</el-tag>
                    </div>

                    <!-- 选择日期 -->
                    <div class="dataVue margin10">
                        <div class="label">发布时间</div>
                        <el-radio v-model="dateType" :label="1" text-color="#0147fd" fill="#0147fd">特定日期</el-radio>
                        <el-radio v-model="dateType" :label="2">每天</el-radio>
                        <el-radio v-model="dateType" :label="3">周期循环</el-radio>
                        <el-radio v-model="dateType" :label="4">立即发送</el-radio>
                        <!-- 特定日期 -->
                        <template v-if="dateType===1">
                            <div class="flex align_center margin10">
                                <span>选择发布日期时间：</span>
                                <el-date-picker v-model="datetime" type="datetime" placeholder="选择发送日期时间" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :picker-options="disableOptions" @change="dateChange" :editable="false"></el-date-picker>
                            </div>
                        </template>
                        <!-- 每天 -->
                        <template v-if="dateType===2">
                            <div class="flex align_center margin10">
                                <span>选择发布时间：</span>
                                <el-time-picker v-model="everyTime" value-format="HH:mm" format="HH:mm" :picker-options="{ selectableRange: '00:00:00 - 23:59:00' }" placeholder="选择发布时间"  @change="everyTimeChange"></el-time-picker>
                            </div>
                        </template>
                        <!-- 周期循环 -->
                        <template v-if="dateType===3">
                            <div class="flex align_center margin10">
                                <span>选择发布周期：</span>
                                <div class="week" :class="{active: selectDays.includes(o)}" v-for="(o, i) in days" :key="i" @click="selectWeekFun(o)">{{ o }}</div>
                            </div>
                            <div class="flex align_center margin10">
                                <span>选择发布时间：</span>
                                <el-time-picker v-model="time" value-format="HH:mm" format="HH:mm" :picker-options="{ selectableRange: '00:00:00 - 23:59:00' }" placeholder="选择发布时间" @change="timeChange"></el-time-picker>
                            </div>
                        </template>
                        <div class="tip">请注意，您设置的群发时间是任务的开始时间，消息将按队列依次发送，这意味着用户接收消息的时间可能会有所不同，您当前任务：群发100人，整个任务大约需要10分钟完成，预计2024年7月11日10:51开始发送</div>
                    </div>   

                    <div class="messageVue margin10">
                        <div class="label">发布内容</div>
                        <div class="messageItem relative" v-for="(item, index) in msgArray" :key="index" :class="{messageActive: index==msgIndex}">
                            <el-radio v-model="msgArray[index].messageType" :label="1">自定义文本内容</el-radio>
                            <el-radio v-model="msgArray[index].messageType" :label="2">自定义图片内容</el-radio>
                            <el-radio v-model="msgArray[index].messageType" :label="3">自定义视频内容</el-radio>
                            <span class="el-icon-close absolute" style="top: 10px; right: 10px; font-size: 18px; color: #AAA; cursor: pointer;" v-if="index!=0" @click="removeMsgArray(index)"></span>
                            <template v-if="msgArray[index].messageType===1">
                                <div class="flex_between align_center margin10">
                                    <div class="flex align_center">
                                        <span style=" color: #666; font-size: 12px; padding-right: 10px;">使用AI生成内容</span>
                                        <el-switch v-model="msgArray[index].isAi" active-color="#0147fd" inactive-color="#999"></el-switch>
                                    </div>
                                    <div class="flex align_center" v-if="msgArray[index].isAi && (dateType===2 || dateType===3)">
                                        <span style=" color: #666; font-size: 12px; padding-right: 10px;">每次任务都生成差异化的内容</span>
                                        <el-switch v-model="msgArray[index].isDifferent" active-color="#0147fd" inactive-color="#999"></el-switch>
                                    </div>
                                </div>
                                <template v-if="msgArray[index].isAi && !msgArray[index].isDifferent">
                                    <textarea v-model="msgArray[index].describetion" placeholder="请大概描述你需要AI生成的内容需求"></textarea>
                                    <div class="flex align_center" style="padding: 10px 0;">
                                        <span style="color: #AAA; font-size: 12px;">AI生成内容预览</span>
                                        <div class="btn" v-if="msgArray[index].loading">
                                            <span class="el-icon-loading" style="color: #fff;"></span>
                                        </div>
                                        <div class="btn" @click="getAiMsg(index)" v-else>生成</div>
                                    </div>
                                    <textarea v-model="msgArray[index].aiMsg" style="margin-top: 0"></textarea>
                                </template>
                                <textarea v-model="msgArray[index].msg" placeholder="请输入自定义文本内容" v-if="!msgArray[index].isAi"></textarea>
                                <textarea v-model="msgArray[index].msg" placeholder="请输入提示词，AI根据提示词生成内容" v-if="msgArray[index].isAi && msgArray[index].isDifferent"></textarea>
                            </template>
                            <template v-if="msgArray[index].messageType===2">
                                <div class="flex">
                                    <div class="uploadVue flex_center align_center relative">
                                        <span class="el-icon-loading" v-if="msgArray[index].loading"></span>
                                        <template v-else>
                                            <span class="el-icon-plus" style="color: #AAA;"></span>
                                            <span style="color: #AAA; padding-left: 5px;">选择图片</span>
                                            <input ref="clearRef" class="fileBtn" type="file" id="fileupload" accept=".jpg, .png, .jpeg" @change="imgChange($event, index)"/>
                                        </template>
                                    </div>
                                    <div class="show flex align_center" v-if="msgArray[index].imgName">
                                        <span>{{ msgArray[index].imgName.split('/')[msgArray[index].imgName.split('/').length-1] }}</span>
                                        <span class="el-icon-close" style="padding-left: 5px; font-size: 16px; cursor: pointer;" @click="msgArray[index].imgName=''"></span>
                                    </div>
                                </div>
                            </template>
                            <template v-if="msgArray[index].messageType===3">
                                <div class="flex">
                                    <div class="uploadVue flex_center align_center relative">
                                        <span class="el-icon-loading" v-if="msgArray[index].loading"></span>
                                        <template v-else>
                                            <span class="el-icon-plus" style="color: #AAA;"></span>
                                            <span style="color: #AAA; padding-left: 5px;">选择视频</span>
                                            <input ref="clearRef" class="fileBtn" type="file" id="fileupload" accept=".mp4" @change="videoChange($event, index)"/>
                                        </template>
                                    </div>
                                    <div class="show flex align_center" v-if="msgArray[index].videoName">
                                        <span>{{ msgArray[index].videoName.split('/')[msgArray[index].videoName.split('/').length-1] }}</span>
                                        <span class="el-icon-close" style="padding-left: 5px; font-size: 16px; cursor: pointer;" @click="msgArray[index].videoName=''"></span>
                                    </div>
                                </div>
                            </template>
                            </div>
                        <div class="messageAdd" @click="addMessage" v-if="msgArray.length<5">再加一条</div>
                    </div>
                </div> 

               <!-- 底部 -->
               <div class="botVue flex_between align_center">
                    <div class="paginationVue"></div>
                    <div class="flex align_center">
                        <el-button size="mini" type="cancel" @click="current=1">上一步</el-button>
                        <el-button size="mini" type="next" @click="nextFun(2)">下一步</el-button>
                    </div>
                </div>     
            </template>

            <!-- 第三步 -->
            <template v-if="current===3">
                <div class="inpContent">
                    <div class="selectVue ">
                        <el-tag v-for="tag in $store.state.selectList" :key="tag.name" closable type="info" size="mini" @close="handleClose(tag)">{{tag.type===0 ? tag.friendWechatName : tag.groupName}}</el-tag>
                    </div>
                    <div class="box margin10">
                        <span style="color: #333;" v-if="dateType==1">发布时间：{{ this.datetime }}</span>
                        <span style="color: #333;" v-if="dateType==2">发布时间：每天 {{ this.everyTime }}</span>
                        <span style="color: #333;" v-if="dateType==3">发布时间：每周{{ this.selectDays.join(",")}} {{ this.time }}</span>
                        <span style="color: #333;" v-if="dateType==4">发布时间：立即发送</span>
                        <div class="msgArray margin10" v-for="(item, index) in msgArray" :key="index">
                            <span style="color: #333;">发布消息看类型：{{ ["文本", "图片", "视频"][item.messageType-1] }}</span>
                            <div style="color: #333; padding-top: 10px;" v-if="item.messageType==1">{{ item.isDifferent ? "AI发布消息内容的提示词" : "发布消息内容"}}：{{ item.isAi ? (item.isDifferent ? item.msg : item.aiMsg) : item.msg }}</div>
                            <div style="color: #333; padding-top: 10px;" v-if="item.messageType==2">发布消息内容：{{ item.imgName.split('/')[item.imgName.split('/').length-1] }}</div>
                            <div style="color: #333; padding-top: 10px;" v-if="item.messageType==3">发布消息内容：{{ item.videoName.split('/')[item.videoName.split('/').length-1] }}</div>
                        </div>
                    </div>
                </div>
                <!-- 底部 -->
                <div class="botVue flex_between align_center">
                    <div class="paginationVue"></div>
                    <div class="flex align_center">
                        <el-button size="mini" type="cancel" @click="current=2">上一步</el-button>
                        <el-button size="mini" type="next" @click="nextFun(3)">
                            <span class="el-icon-loading" v-if="loading"></span>
                            <span v-else>发送</span>
                        </el-button>
                    </div>
                </div>
            </template>  
        </div>  
        <recordVue :dialogTableVisible="recordDialog" @beforeClose="recordDialog=false" @getFriends="getFriends" ref="recordRef"></recordVue>
        <friendsVue :dialogTableVisible="friendsDialog" @beforeClose="friendsDialog=false" @recordCallback="recordCallback" @back="back" ref="friendRef"></friendsVue>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { toast, formatTime } from '@/common/tools'
import { post } from '@/common/request'
import recordVue from './components/record.vue';
import friendsVue from './components/friends.vue';
export default {
    components: {
        recordVue,
        friendsVue
    },
    data(){
        return {
            value: "",
            current: 1,
            categoryList: [],
            categoryId: "",
            category: "",
            pageNum: 1,
            pageSize: 20,
            list: [],
            total: 0,
            tag: "",
            key: "",
            
            repeatTypeList: [],
            tags: ["高意向","中意向","低意向","了解产品详情", "询问价格", "询问使用方法", "询问发货时间", "询问售后服务", "非常满意", "满意", "一般", "不满意", "非常不满意", "产品质量", "发货时间", "售后服务", "使用问题", "价格问题", "新客户", "忠实客户", "活跃", "潜在", "流失"],
            tag: "",

            chatTypes: [{ name: "私聊", type: 0 }, { name: "群聊", type: 1}],
            chatType: "",
            chatName: "",

            selectName: "全部",
            words: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#"],
            isAll: false,
            allFriend: [],

            dateType: 1,
            datetime: "",
            disableOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7
                },
            },
            days: ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            selectDays: [],
            time: "",
            everyTime: "",
            msg: "",
            msgArray: [{
                messageType: 1,
                isAi: false,
                msg: "",
                describetion: "",
                aiMsg: "",
                imgName: "",
                videoName: "",
                isDifferent: false,
                loading: false,
            }],
            isLoading: false,
            loading: false,
            msgIndex: null,
            isCurrentPage: false,
            applicationId: "",
            recordDialog: false,
            friendsDialog: false,
            selectLoading: false,
        }
    },
    created(){
        this.getList()
        this.getCategoryList()
        this.getAllFriend()
    },
    computed: {
        ...mapState({
            currentWeChat: state=> state.currentWeChat,
            weChatList: state=> state.weChatList,
        })
    },
    beforeDestroy(){
        this.$store.state.selectList = []
        this.tag = ""
        this.categoryId = ""
        this.chatType = ""
        this.selectName = ""
        this.chatName = ""
        this.pageNum = 1
        this.category = ""
        this.msgArray = [{
            messageType: 1,
            isAi: false,
            msg: "",
            describetion: "",
            aiMsg: "",
            imgName: "",
            videoName: "",
            loading: false,
            isDifferent: false,
        }]
        this.datetime = ""
        this.loading = false
    },
    methods: {
        // 筛选标签
        handleTagCommand(command){
            this.tag = command
            this.selectName = ""
            this.reStart()
        },

        recordCallback(){
            this.friendsDialog = false
        },

        // 好友明细弹框
        getFriends(data){
            console.log(data,"data")
            this.recordDialog = false
            this.friendsDialog = true
            this.$refs.friendRef.getList(data)
            this.$refs.friendRef.getAllList(data)
        },

        back(){
            this.friendsDialog = false
            this.recordDialog = true
        },

        toChoose(){
            this.recordDialog=true
            this.$refs.recordRef.getList(this.$route.query.taskWeChatId, this.$route.query.taskWeChatName)
        },

        // 筛选分组
        handleCategoryCommand(command){
            this.categoryId = command.id
            this.category = command.name
            this.selectName = ""
            this.reStart()
        },

        // 筛选聊天
        handleChatCommand(command){
            this.chatType = command.type
            this.chatName = command.name
            this.selectName = ""
            this.reStart()
        },

        reStart(){
            this.list = []
            this.pageNum = 1
            this.getList()
            this.getAllFriend()
        },

        // 群发图片
        imgChange(e, index){
            console.log(e, index)
            var file = e.target.files[0];
            var formData = new FormData()
            formData.append("file", file)
            this.msgArray[index].loading = true
            this.$forceUpdate()
            post("/front/search/uploadImage", formData).then(res=>{
                if(this.$refs.clearRef.value) this.$refs.clearRef.value = ''; // 清空file文件
                this.msgArray[index].loading = false
                this.$forceUpdate()
                if(res.data.code===0) this.msgArray[index].imgName = res.data.obj 
            })
        },

        // 群发视频
        videoChange(e, index){
            console.log(e, index)
            var file = e.target.files[0];
            var formData = new FormData()
            formData.append("file", file)
            this.msgArray[index].loading = true
            this.$forceUpdate()
            post("/front/search/uploadVideo", formData).then(res=>{
                if(this.$refs.clearRef.value) this.$refs.clearRef.value = ''; // 清空file文件
                this.msgArray[index].loading = false
                this.$forceUpdate()
                if(res.data.code===0) this.msgArray[index].videoName = res.data.obj
            })
        },

        // 快速搜索
        fastSearch(index, str){
            switch(index){
                case 1:
                    this.selectName = str
                    this.list = []
                    this.chatType = ""
                    this.getList()
                break;
                case 2:
                this.selectName = str
                    this.list = []
                    this.chatType = ""
                    this.getList()
                break;
                case 3:
                    this.selectName = str
                    this.list = []
                    this.getList()
                break;
            }
        },

        // 获取分组列表
        getCategoryList(){
            this.$post("/front/wechat/friend/categoryList").then(res=>{
                if(res.data.code===0) {
                    this.categoryList = res.data.obj
                }
            })
        },

        // 选择周期循环
        selectWeekFun(o){
            if(this.selectDays.includes(o)) {
                this.selectDays = this.selectDays.filter(item=>{
                    return item != o
                })
            }else{
                this.selectDays.push(o)
            }
        },

        // 选择日期时间
        dateChange(e){
            console.log(e)
            let timestamp = new Date(e).getTime()
            console.log(timestamp)
            this.datetime = formatTime(timestamp, "YMDHM")
            console.log(this.datetime)
        },

        // 选择时间
        timeChange(e){
            console.log(e)
            this.time = e
        },

        everyTimeChange(e){
            console.log(e)
            this.everyTime = e
        },

        // 单个选择好友
        selectFun(item){
            this.$store.state.selectList.push(item)
            this.isCurrentPageFun()
        },

        // 删除发送消息
        removeMsgArray(index){
            this.msgArray = this.msgArray.slice(0, index).concat(this.msgArray.slice(index + 1));
        },

        // 移除选择好友
        removeFun(item){
            this.isAll = false
            this.$store.state.selectList = this.$store.state.selectList.filter(o=>{
                return item.id != o.id
            })
            this.isCurrentPageFun()
        },

        // 选择所有
        selectAll(){
            if(this.selectLoading) return
            this.selectLoading = true
            this.$post("/front/wechat/friend/friendList", {
                pageNum: 1,
                pageSize: 10000,
                userWechatPrimaryId: this.$route.query.taskWeChatId,
                userWechatName: this.$route.query.taskWeChatName,
                blacklist: 0,
                categoryId: this.categoryId,
                tag: this.tag,
                content: this.key,
                type: this.chatType,
            }).then(res=>{
                this.selectLoading = false
                if(res.data.code===0) {
                    this.$store.state.selectList = res.data.obj.list
                    this.isAll = true
                    this.isCurrentPage = true
                }
            })
        },

        // 全选当前页
        selectCurrentPage(){
            this.isCurrentPage = true
            for(let i=0; i<this.list.length; i++){
                if(!JSON.stringify(this.$store.state.selectList).includes(JSON.stringify(this.list[i]))) {
                    this.$store.state.selectList.push(this.list[i])
                }
            }
        },

        // 取消全选当前页
        cancelCurrentPage(){
            this.isCurrentPage = false
            for(let i=0; i<this.list.length; i++){
                this.$store.state.selectList = this.$store.state.selectList.filter(o=>{
                    return this.list[i].id != o.id
                })
            }
        },

        
        // 获取好友列表
        getList(){
            this.$post("/front/wechat/friend/friendList", {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                userWechatPrimaryId: this.$route.query.taskWeChatId,
                categoryId: this.categoryId,
                tag: this.tag,
                content: this.key,
                type: this.chatType,
                userWechatName: this.$route.query.taskWeChatName,
                blacklist: 0
            }).then(res=>{
                if(res.data.code===0) {
                    this.list = res.data.obj.list
                    this.total = res.data.obj.total
                    this.isCurrentPageFun()
                }
            })
        },

        // 判断当前页是否全选
        isCurrentPageFun(){
            for(let i=0; i<this.list.length; i++) {
                if(!JSON.stringify(this.$store.state.selectList).includes(JSON.stringify(this.list[i]))) {
                    this.isCurrentPage = false
                    return 
                }
            }
            this.isCurrentPage = true
        },


        // 一次性获取所有好友，方便全选操作
        getAllFriend(){
            this.$post("/front/wechat/friend/friendList", {
                pageNum: 1,
                pageSize: 10000,
                userWechatPrimaryId: this.$route.query.taskWeChatId,
                userWechatName: this.$route.query.taskWeChatName,
                blacklist: 0,
                categoryId: this.categoryId,
                tag: this.tag,
                content: this.key,
                type: this.chatType,
            }).then(res=>{
                if(res.data.code===0) {
                    this.allFriend = res.data.obj.list
                    this.canAll = true
                    console.log("一次性加载所有好友已完成")
                }
            })
        },

        // 下一步
        nextFun(index){
            if(index===1) {
                if(this.$store.state.selectList.length===0) return toast(1, "请至少选择一个发送对象")
                this.current = 2
            }
            if(index===2) {
                if(this.$store.state.selectList.length===0) return toast(1, "请至少选择一个发送对象")
                if(this.dateType===1 && !this.datetime) return toast(1, "请选择发布日期")
                if(this.dateType===1) {
                    let timestamp = new Date(this.datetime).getTime()/1000
                    let now = Math.ceil(new Date().getTime()/1000)
                    if(timestamp - now <= 0) return toast(1, "选择的发布时间小于当前时间，请重新选择")
                }
                if(this.dateType===2 && !this.everyTime) return toast(1, "请选择发布时间")
                if(this.dateType===3 && this.selectDays.length===0) return toast(1, "请选择发布周期")
                if(this.dateType===3 && !this.time) return toast(1, "请选择发布时间")
                for(let i=0; i<this.msgArray.length; i++) {
                    if(this.msgArray[i].messageType===1 && !this.msgArray[i].isAi && !this.msgArray[i].msg) {
                        toast(1, "请输入自定义文本内容")
                        this.msgIndex = i
                        this.clearError()
                        return 
                    }
                    if(this.msgArray[i].messageType===1 && this.msgArray[i].isAi && !this.msgArray[i].isDifferent && !this.msgArray[i].aiMsg) {
                        toast(1, "请先生成AI内容")
                        this.msgIndex = i
                        this.clearError()
                        return 
                    }
                    if(this.msgArray[i].messageType===1 && this.msgArray[i].isAi && this.msgArray[i].isDifferent && !this.msgArray[i].msg) {
                        toast(1, "请输入提示词，AI根据提示词生成内容")
                        this.msgIndex = i
                        this.clearError()
                        return 
                    }
                    if(this.msgArray[i].messageType===2 && !this.msgArray[i].imgName) {
                        this.msgIndex = i
                        this.clearError()
                        toast(1, "请上传图片文件")
                        return 
                    }
                    if(this.msgArray[i].messageType===3 && !this.msgArray[i].videoName) {
                        this.msgIndex = i
                        this.clearError()
                        toast(1, "请上传视频文件")
                        return 
                    }
                }
                this.current = 3
                console.log(this.msgArray)
            }
            if(index===3) {
                if(this.$store.state.selectList.length===0) return toast(1, "请至少选择一个发送对象")
                this.submitFun()
            }
        },

        clearError(){
            setTimeout(() => {
                this.msgIndex = null
            }, 3000);
        },

        // 创建定时消息
        submitFun(){
            let array = []
            for(let i=0; i<this.$store.state.selectList.length; i++){
                array.push(this.$store.state.selectList[i].id)
            }
            // 处理时间和循环类型
            let cycle = ""
            let timing = ""
            console.log(this.dateType)
            if(this.dateType===1) {
                timing = this.datetime
                console.log(this.datetime,"this.datetime")
            } else if(this.dateType===2) {
                console.log(this.everyTime,"this.everyTime")
                timing = this.everyTime
            }else if(this.dateType===3) {
                console.log(this.time,"this.time")
                timing = this.time
                cycle = this.selectDays.join(",")
            }
            // 处理消息
            let contentList = []
            for(let i=0; i<this.msgArray.length; i++) {
                let content = ""
                let aiContent = ""
                if(this.msgArray[i].messageType===1) {
                    if(this.msgArray[i].isAi) {
                        if(this.msgArray[i].isDifferent) {
                            content = this.msgArray[i].msg
                        }else{
                            aiContent = this.msgArray[i].aiMsg
                        }
                    }else{
                        content = this.msgArray[i].msg
                    } 
                }
                if(this.msgArray[i].messageType===2) content = this.msgArray[i].imgName
                if(this.msgArray[i].messageType===3) content = this.msgArray[i].videoName
                let obj = {
                    type: this.msgArray[i].messageType,
                    aiAutoGenerate: this.msgArray[i].isAi,
                    aiAutoEveryday: this.msgArray[i].isDifferent,
                    content: content,
                    aiContent: aiContent
                }
                console.log(obj)
                contentList.push(obj)
            }
            console.log(contentList,"contentList")
            this.loading = true
            post("/front/timing/createTimingTask", {
                wechatId: this.$route.query.taskWeChatId,
                wechatName: this.$route.query.taskWeChatName,
                receiverIds: array,
                name: this.$route.query.taskName,
                type: this.dateType,
                cycle: cycle,
                timing: timing,
                contentList: contentList
            }).then(res=>{
                console.log(res)
                this.loading = false
                if(res.data.code===0) {
                    toast(0, "创建成功")
                    this.$router.go(-1)
                }else{
                    toast(1, res.data.msg)
                }
            })
        },

        handleClose(tag) {
            this.isAll = false
            this.$store.state.selectList.splice(this.$store.state.selectList.indexOf(tag), 1);
        },

        addMessage(){
            this.msgArray.push({
                messageType: 1,
                isAi: false,
                msg: "",
                describetion: "",
                aiMsg: "",
                imgName: "",
                videoName: "",
                loading: false,
                isDifferent: false,
            })
            // 滑动到聊天最底部
            this.$nextTick(()=>{
                let dom = this.$refs.msgRef
                console.log(dom)
                dom.scrollTo({ top: dom.scrollHeight, behavior: 'smooth' });
            })
        },

        // 定时消息重复类型
        getRepeatTypeList(){
            this.$post("/front/timedMessage/repeatTypeList").then(res=>{
                this.repeatTypeList = res.data.obj
            })
        },

        // 好友分页
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.friendPageNum = val
            this.getFriendList()
        },

        selectWeekFun(o){
            if(this.selectDays.includes(o)) {
                this.selectDays = this.selectDays.filter(item=>{
                    return item != o
                })
            }else{
                this.selectDays.push(o)
            } 
        },

        fileChange(event, index){
            console.log(index)
            const file = event.target.files[0];
            this.contentList[index].img = this.getFileUrl(file)
            let formData = new FormData()
            formData.append("file", file)
            this.loading = true
            post("/front/search/uploadFile", formData).then(res=>{
                this.contentList[index].imgUrl = res.data.obj
            }) 
        },

        getFileUrl(file) {
            var url;
            var agent = navigator.userAgent;
            if (agent.indexOf("MSIE") >= 1 || agent.indexOf("NET")!=-1) {
                url = window.URL.createObjectURL(file);
            } else if (agent.indexOf("Firefox") > 0) {
                url = window.URL.createObjectURL(file);
            } else if (agent.indexOf("Chrome") > 0) {
                url =window.webkitURL.createObjectURL(file);
            }
            return url;
        },

        getAiMsg(index){
            if(!this.msgArray[index].describetion) return toast(1, "请大概描述你需要生成的内容需求")
            if(this.msgArray[index].loading) return
            this.msgArray[index].loading = true
            this.weChatList.forEach(o=>{
                if(o.id==this.$route.query.taskWeChatId) {
                    console.log("this.applicationId = o.applicationId")
                    this.applicationId = o.applicationId
                }
            })
            this.$post("/front/userWechat/returnModelAnswer", {
                applicationId: this.applicationId,
                message: this.msgArray[index].describetion
            }).then(res=>{
                if(res.data.code===0) {
                    console.log(res)
                    this.msgArray[index].loading = false
                    this.msgArray[index].aiMsg = res.data.obj
                }else {
                    this.msgArray[index].loading = false
                    toast(1, res.data.msg)
                }
            })
        },

        handlePageChange(val){
            console.log(`当前页: ${val}`);
            this.pageNum = val
            this.getList()
        },
    }
}
</script>

<style lang="less" scoped>
:deep(.el-button--next) {
    background: #0147fd;
    height: 34px;
    margin-left: 10px;
    span {
        color: #fff !important;
    }
}

:deep(.el-button--cancel) {
    background: #AAA;
    height: 34px;
    span {
        color: #fff !important;
    }
}
:deep(.el-icon-circle-close) {
    font-size: 18px !important;
    color: #409EFF !important;
}
:deep(.el-icon-search:before) {
    color: #AAA !important;
}
:deep(.el-input__inner) {
    border: 1px solid #f5f5f5 !important;
}
:deep(.el-tag--info) {
    margin: 3px;
}
:deep(.el-time-spinner__item) {
    box-sizing: border-box !important;
}
.createVue {
    width: 100%;
    height: 100%;
    padding: 15px;
    .stepVue {
        width: 100%;
        .chooseVue {
            width: 140px;
            height: 36px;
            border-radius: 5px;
            line-height: 36px;
            text-align: center;
            font-size: 13px;
            background: #0147fd;
            color: #fff;
            position: absolute;
            right: 0;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
        }
        .dot {
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background: #EEE;
            line-height: 25px;
            text-align: center;
            color: #999;
            margin-bottom: 10px;
        }
        .active {
            background: #0147fd;
            color: #fff;
        }
        .line {
            width: 150px;
            height: 1px;
            background: #EEE;
            margin-top: 12px;
        }
        span {
            color: #999;
            font-size: 12px;
        }    
        .textActive {
            color: #0147fd;
            font-weight: 600; 
        }
    }
    .contentVue {
        width: 100%;
        height: calc(100% - 57px);
        margin-top: 10px;
        .searchVue {
            width: 100%;
            height: 50px;
            padding-top: 10px;
            .active {
                color: #0147fd;
                font-weight: 600;
            }
        }
        .listVue {
            width: 100%;
            height: calc(100% - 57px - 110px);
            margin-top: 10px;
            .content {
                width: 100%;
                height: calc(100% - 47px);
                .thVue {
                    width: 100%;
                    height: 40px;
                    background: #f5f5f5;
                }
                .tdContent {
                    width: 100%;
                    height: calc(100% - 40px);
                    // background: #000;
                    overflow: scroll;
                    .tdVue {
                        width: 100%;
                        height: 50px;
                        border-bottom: 1px solid #f5f5f5;
                    }
                    .tdVue:hover {
                        background: #f5f5f5;
                    }
                }
                .tdContent::-webkit-scrollbar {
                    width: 0;
                    height: 0;
                }
            }
            .botVue {
                width: 100%;
                height: 50px;
                .allBtn {
                    width: 100px;
                    height: 34px;
                    line-height: 34px;
                    text-align: center;
                    background: #0147fd;
                    border-radius: 5px;
                    cursor: pointer;
                    margin-left: 10px;
                    span {
                        color: #fff;
                        font-size: 12px;
                    }
                }
            }
        }
        .selectVue {
            width: 100%;
            height: 100px;
            border: 1px solid #f5f5f5;
            border-radius: 5px;
            padding: 6px;
            margin-top: 10px;
            overflow-y: scroll;
        }
        .selectVue::-webkit-scrollbar {
            width: 0;
            height: 0;
        }
        .inpContent {
            width: 100%;
            height: calc(90vh - 47px - 75px);
            overflow-y: scroll;
            padding-bottom: 10px;
            .box {
                width: 100%;
                border: 1px solid #f5f5f5;
                border-radius: 5px;
                padding: 10px;
                .msgArray {
                    width: 100%;
                    border: 1px solid #f5f5f5;
                    border-radius: 5px;
                    padding: 10px;
                }
            }
            .selectVue {
                width: 100%;
                height: 100px;
                border: 1px solid #f5f5f5;
                border-radius: 5px;
                padding: 6px;
                margin-top: 10px;
                overflow-y: scroll;
            }
            .selectVue::-webkit-scrollbar {
                width: 0;
                height: 0;
            }
            .dataVue {
                width: 100%;
                border: 1px solid #f5f5f5;
                border-radius: 5px;
                padding: 10px;
                .label {
                    color: #111;
                    font-weight: 600;
                    font-size: 12px;
                    padding-bottom: 15px;
                }
                .week {
                    width: 80px;
                    height: 40px;
                    border: #f5f5f5  1px solid;
                    margin-right: 10px;
                    border-radius: 4px;
                    line-height: 40px;
                    text-align: center;
                    color: #999;
                    cursor: pointer;
                }

                .active {
                    background: #0147fd;
                    color: #fff;
                }

                .tip {
                    color: #AAA;
                    font-size: 12px;
                    padding-top: 10px;
                    line-height: 1.4;
                }
            }
            .messageVue {
                width: 100%;
                border: 1px solid #f5f5f5;
                border-radius: 5px;
                padding: 10px;
                .label {
                    color: #111;
                    font-weight: 600;
                    font-size: 12px;
                    padding-bottom: 15px;
                }
                .messageAdd {
                    width: 100%;
                    height: 40px;
                    text-align: center;
                    line-height: 40px;
                    background: #f5f5f5;
                    margin-top: 10px;
                    color: #AAA;
                    cursor: pointer;
                    font-size: 12px;
                }
                .messageItem {
                    width: 100%;
                    border: 1px solid #f5f5f5;
                    border-radius: 5px;
                    padding: 10px;
                    margin-top: 10px;
                    .label {
                        color: #111;
                        font-weight: 600;
                        font-size: 12px;
                        padding-bottom: 15px;
                    }
                    .btn {
                        width: 60px;
                        height: 32px;
                        background: #0147fd;
                        border-radius: 4px;
                        margin-left: 6px;
                        line-height: 32px;
                        text-align: center;
                        color: #fff;
                        font-size: 12px;
                        cursor: pointer;
                    }
                    .uploadVue {
                        width: 120px;
                        height: 38px;
                        background: #f5f5f5;
                        border-radius: 5px;
                        margin-top: 10px;
                        cursor: pointer;
                        .fileBtn {
                            width: 100%;
                            height: 100%;
                            position: absolute;
                            left: 0;
                            top: 0;
                            opacity: 0;
                            cursor: pointer;
                            z-index: 98;
                            border: none;
                            outline: none;
                        }
                    }
                    .show {
                        padding: 0 10px;
                        background: #f5f5f5;
                        border-radius: 5px;
                        margin-top: 10px;
                        margin-left: 10px;
                        span {
                            color: #AAA;
                        }
                    }
                    textarea {
                        width: 100%;
                        height: 60px;
                        border: #f5f5f5 1px solid;
                        display: block;
                        box-sizing: border-box;
                        resize: none;
                        border-radius: 4px;
                        margin-top: 10px;
                        line-height: 1.4;
                        font-family: PingFangSC, PingFang SC;
                        padding: 10px;
                        font-size: 13px;
                    }
                    textarea::-webkit-scrollbar {
                        width: 0;
                        height: 0;
                    }
                    ::-webkit-input-placeholder { /* WebKit browsers */
                        color: #AAA;
                        font-size: 13px;
                        font-family: PingFangSC, PingFang SC;
                    }
                    :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
                        color: #AAA;
                        font-size: 13px;
                        font-family: PingFangSC, PingFang SC;
                    }
                    ::-moz-placeholder { /* Mozilla Firefox 19+ */
                        color: #AAA;
                        font-size: 13px;
                        font-family: PingFangSC, PingFang SC;
                    }
                    :-ms-input-placeholder { /* Internet Explorer 10+ */
                        color: #AAA;
                        font-size: 13px;
                        font-family: PingFangSC, PingFang SC;
                    }
                }
                .messageActive {
                    border: 1px solid #f4ea2a;
                }
                
            }
            
        }
        .inpContent::-webkit-scrollbar {
            width: 0;
            height: 0;
        }
    }
}

</style>